package com.pro.bl.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.pro.bl.dto.PersonDTO;
import com.pro.bl.dto.PersonDTO.Status;
import com.pro.dl.dao.service.PersonDao;
import com.pro.dl.exception.PersonAlreadyExists;
import com.pro.dl.exception.StorageException;
import com.pro.dl.exception.UserDoesNotExists;
import com.pro.dl.pojo.Person;

public class SignupServiceImpl {

	static Logger logger = LogManager.getLogger(SignupServiceImpl.class);

	// Autowired.
	EmailService emailService;

	PersonDao personDao;

	/**
	 * save an instance of person in database and send email for verification.
	 * All the verification should be done prior of calling this method.
	 * Duplicate Username can be thrown as exception.
	 * 
	 * @param person
	 */
	public PersonDTO signUpPerson(Person person) throws StorageException {
		Status status;
		Person result = person;
		try {
			result = personDao.savePerson(person);
			status = Status.SUCCESSFUL;
		} catch (PersonAlreadyExists e) {
			logger.error("user you are trying to save already exists .", e);
			status = Status.DUPLICATE_USER;
		}
		return new PersonDTO(result, status);
	}

	public PersonDTO validateSignup(String userName, String token)
			throws StorageException {
		Status status = null;
		Person person = null;
		try {
			person = personDao.validateUser(userName, token);
			status = Status.SUCCESSFUL;
		} catch (UserDoesNotExists e) {
			logger.error("Validating user does not exists .", e);
			status = Status.NO_USERNAME;
		}
		return new PersonDTO(person, status);
	}

	public PersonDTO validateQuestionAndAnswer(String userName, String question, String answer) throws StorageException {

		Status status = null;
		Person person = null;
		try {
			person = personDao.validateQNA(userName, question, answer);
			status = Status.SUCCESSFUL;
		} catch (UserDoesNotExists e) {
			logger.error("Validating user does not exists .", e);
			status = Status.NO_USERNAME;
		}
		return new PersonDTO(person, status);
	}

}
